package com.jlhlyby.concurrence;

/**
 * 多个线程轮流打数
 */
public class MultiThreadPrintNum {
    public static void main(String[] args) {
        int total = 5;
        for (int i = 0; i < total; i++) {
            new PrintThread(i, total, 100).start();
        }
    }

    static class PrintThread extends Thread {
        public static final String lock = "";
        public static volatile int sum = 1;
        public static volatile int flag = 0;
        int index;
        int totalThread;
        int maxSum;

        public PrintThread(int index, int totalThread, int maxSum) {
            this.index = index;
            this.totalThread = totalThread;
            this.maxSum = maxSum;
        }

        @Override
        public void run() {
            synchronized (lock) {
                while (sum <= maxSum) {
                    if (flag == index) {
                        System.out.println(getName() + " : " + sum++);
                        flag = ++flag % totalThread;
                    }
                    //多个线程要都唤起去锁竞争
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }
}
